<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/11
 * Time: 14:27
 */

namespace app\controllers;

use app\models\Staff;
use yii;
use app\models\AccountMoney;
use app\models\Income;
use app\service\IncomeService;

class IncomeController extends ApiBaseController
{
    public function actionList()
    {
        $p = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where['pay_from'] = is_numeric(yii::$app->request->get('pay_type')) ? yii::$app->request->get('pay_type') : 0;
        $where['begin_time'] = yii::$app->request->get('begin_time');
        $where['end_time'] = yii::$app->request->get('end_time');
        $where['service_name'] = trim(yii::$app->request->get('service_name', ''));
        $where['number'] = trim(yii::$app->request->get('number', ''));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name', ''));
        $where['invocie_num'] = trim(yii::$app->request->get('invocie_num', ''));
        $where['property_p'] = yii::$app->request->get('property_p', '');
        $service = new IncomeService();
        $list = $service->apiList($p, $s, $where);
        return json_encode($list);
    }

    public function actionCommon()
    {
        $service = new IncomeService();
        $list = $service->incomeBase();
        return json_encode($list);
    }

    public function actionInsertBatch()
    {
        $data = yii::$app->request->post('data');
        $data = json_decode($data, true);
        foreach ($data as $k => $v) {
            if (empty($v['date'])) {
                unset($data[$k]);
            }
        }
        //获取当前余额信息
        //开始事务
        $tr = yii::$app->db->beginTransaction();
        try {
            $model = new AccountMoney();
            $db = new Income();

            $list = $model->all();
            foreach ($data as $v) {
                $income = isset($v['in_come']) ? $v['in_come'] : 0;
                $total = isset($v['total_fee']) ? $v['total_fee'] : 0;
                $fee = isset($v['fee']) ? $v['fee'] : 0;
                $pay = $income + $total + $fee;
                $money = $list[$v['pay_from']]['money'] + $pay;
                $list[$v['pay_from']]['money'] = $money;
                $model->save(['money' => $money], ['id' => $v['pay_from']]);
                $v['remain_money'] = $money;
                $db->insert($v);
            }
            $tr->commit();
            $output = ['code' => 1, 'msg' => '添加成功'];
        } catch (\Exception $e) {

            $tr->rollBack();
            $output = ['code' => 0, 'msg' => $e->getMessage()];
        }
        $sql = 'UPDATE jingsourcing_income SET pid=id WHERE pid=0';
        yii::$app->db->createCommand($sql)->execute();
        //结束事务
        return json_encode($output);
    }

    public function actionSplitRecord()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'not allowd']);
        }
        $data['id'] = (int)yii::$app->request->post('id');
        $data['in_come'] = yii::$app->request->post('in_come', 0);
        $data['total_fee'] = yii::$app->request->post('total_fee', 0);
        $data['fee'] = yii::$app->request->post('fee', 0);
        $data['invocie_num'] = yii::$app->request->post('invoice', '');
        $service = new IncomeService();
        $re = $service->insert_split($data);
        $model = new Income();
        $model->validateMoney($data['id']);
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '拆分成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '拆分失败']);
        }

    }

    /**
     * 月份数据分析
     */
    public function actionAnalyse()
    {
        $year = yii::$app->request->get('year', date('Y'));
        $model = new Income();
        $where = [];
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['staff'] = $this->user['job_number'];
        }
        $list = $model->sumIncomeEveryMonth($year, $where);
        foreach ($list as $k => $v) {
            $list[$k]['income'] = (float)$v['income'];
        }
        $total = array_sum(array_column($list, 'income'));
        $list[] = ['m' => '统计', 'income' => round($total,2)];
        return \json_encode(['list' => $list]);
    }

    /**
     * 当月业务员收款分析
     */
    public function actionStaff()
    {
        $month = yii::$app->request->get('month', date('Y-m'));
        $where = [];
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['staff'] = $this->user['job_number'];
        }
        $model = new Income();
        $list = $model->sumIncomebyMonth($month, $where);
        $model = new Staff();
        $staff = $model->get_all_saleman();
        foreach ($list as $k => $v) {
            $list[$k]['income'] = (float)$v['income'];
            foreach ($staff as $v2) {
                if ($v['service_name'] == $v2['job_number']) {
                    $list[$k]['name'] = $v2['name'];
                }
            }
        }
        usort($list, function ($a, $b) {
            if ($a > $b) {
                return 1;
            }
            return false;
        });
        $total = array_sum(array_column($list, 'income'));
        $list[] = ['income' => round($total,2), 'name' => '统计'];
        return \json_encode(['list' => $list]);
    }
}
